<?php

// **************************************************************
// | Name： 星空框架 订单微服务
// **************************************************************
// | Version: V5.0
// **************************************************************
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// **************************************************************
// | City: 青岛
// **************************************************************
// | Time: 2021-08-31 15:11
// **************************************************************
declare(strict_types=1);

namespace app\common\services;

use app\common\model\Address as AddressModel;
use app\common\model\BackMoney as BackMoneyModel;
use app\common\model\Car as CarModel;
use app\common\model\Goods as GoodsModel;
use app\common\model\SpecPrice as SpecPriceModel;
use app\common\model\Store as StoreModel;
use app\common\model\Order as OrderModel;
use app\common\model\SubOrder as SubOrderModel;
use app\common\model\UserUpLog as UserUpLogModel;
use app\common\model\OrderGoodsRefund as OrderGoodsRefundModel;
use app\common\model\GoodsOrder as GoodsOrderModel;
use app\common\model\RefundOrder as RefundOrderModel;
use app\common\services\UserServices;
use app\common\services\OrderServices;
use app\common\model\User as UserModel;
use app\common\services\FinanceServices;
use app\common\controller\Unionpay;
use app\common\controller\Alipay;
use app\common\services\SendMsg;
use app\common\services\Task;
use think\facade\Db;

/**
 * @xk 订单服务
 */
class OrderServices
{
    /**
     * @xk 整合订单数据
     *
     * @method createOrderData
     *
     * @param [type] $car_id_str [description]
     * @param [type] $user_sn    [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-11T13:59:02+080
     */
    public static function createOrderData($car_id, $address_id, $user_sn, $befrom, $shipping_type=1, $l_user_sn = '')
    {
        $goodsModel = new GoodsModel();
        $addressModel = new AddressModel();
        $orderModel = new OrderModel();
        $goodsOrderModel = new GoodsOrderModel();
        $storeModel = new StoreModel();
        $specPriceModel = new SpecPriceModel();
        $shippingServices = new ShippingServices();
        $subOrderModel = new SubOrderModel();
        $carModel = new CarModel();
        $userModel = new UserModel();
        $result = [];
        $order_data = [];
        $sub_order_data = [];
        $order_goods_data = [];
        $order_sn = $orderModel->getCodeNo(date('YmdHi'), 20, 1, 'order_sn');
        $is_edit_price = 0;
        if (!$car_id) {
            throw new \think\Exception("要结算的数据不存在，请重试", 404);
        }
        $address_info = $addressModel
                    ->field('`address_id`,`province_code`,`city_code`,`area_code`,`street_code`,`name`,`tel`,`province`,`city`,`area`,`street`,`address`')
                    ->find($address_id);
        if (!$address_info && $shipping_type == 1) {
            throw new \think\Exception("请选择收货地址", 404);
        }
        $is_buy = $userModel->where([['user_sn','=',$user_sn]])->value('is_buy');
        // 开始执行 购物车数据的查询
        // 获取产品数据
        $condition = [];
        $condition[] = ['car.user_sn', '=', $user_sn];
        $condition[] = ['car.status', '=', 0]; // 当前未处理的的购物车数据
        $condition[] = ['car.car_id', 'in', $car_id]; // 当前未处理的的购物车数据
        $car_list = $carModel
                ->alias('car')
                ->leftJoin('store s', 's.store_id=car.store_id')
                ->leftJoin('goods g', 'g.goods_id=car.goods_id and g.`is_onsell`=1')
                ->leftJoin('specPrice sp', 'car.goods_id=sp.goods_id and sp.sku_key = car.spec_key and sp.spec_price_id = car.spec_price_id')
                ->where($condition)
                ->field('car.`car_id`,car.`goods_id`,car.`goods_name`,car.`goods_pic`,car.`spec_key`,car.`spec_value`,car.`goods_price`,car.`spec_price_id`,car.`buy_num`,s.`store_name`,s.`store_id`,car.`achievement_bili`,car.`bonus_type`,car.`bonus_price`,car.`next_bonus_price`,car.`is_buy`,g.`is_supper`')
                ->withAttr('goods_pic', function ($value, $data) {
                    if ($value) {
                        return getShowUrl($value);
                    }
                })
                ->withAttr('goods_stock', function ($value, $data) {
                    return $value>=0 ? $value : $stock;
                })
                ->order('car.car_id desc')
                ->select()
                ->toArray(); // 产品数据获取完成  产品单价
        foreach ($car_list as $key => $value) {
            // 获取仓库信息
            $store_info = $storeModel
                        ->field('`store_id`,`status`,`is_self`')
                        ->find($value['store_id']);
            if (!$store_info || $store_info['status'] != 1) {
                throw new \think\Exception($value['goods_name'].'所属仓库异常，请重新确认订单', 404);
            }
            $goods_info = $goodsModel
                    ->where([['goods_id','=',$value['goods_id']]])
                      ->field('`goods_id`,`store_id`,`goods_name`,`picurl`,`selling_price`,`weight`,`stock`,`is_onsell`,`achievement_bili`,`bonus_type`,`bonus_price`,`next_bonus_price`,`vip_buy_bili`,`goods_sn`,`keywords`')
                      ->find();
            if (!$goods_info || $goods_info['is_onsell'] != 1) {
                throw new \think\Exception("产品".$value['goods_name'].'异常暂时无法提交', 404);
            }
            $car_data = [];
            $value['goods_name'] = $car_data['goods_name'] = $goods_info['goods_name'];
            $value['goods_des'] = $car_data['goods_des'] = $goods_info['keywords'];
            $value['goods_id'] = $car_data['goods_id'] = $goods_info['goods_id'];
            $value['store_id'] = $car_data['store_id'] = $goods_info['store_id'];
            $value['achievement_bili'] = $car_data['achievement_bili'] = $goods_info['achievement_bili'];
            $value['goods_pic'] = $car_data['goods_pic'] = $goods_info['picurl'];
            $value['goods_sn'] = $goods_info['goods_sn'];
            $value['goods_price'] = $car_data['goods_price'] = $goods_info['selling_price'];
            $value['selling_price'] = $car_data['selling_price'] = $goods_info['selling_price'];
            if ($is_buy == 1) {
                $value['goods_price'] = $car_data['goods_price'] = (float)$goods_info['selling_price']*(float)$goods_info['vip_buy_bili'];
                $is_edit_price = 1;
            }
            $value['is_onsell'] = $car_data['is_onsell'] = $goods_info['is_onsell'];
            // 第三步 判断是否存在规格 判断规格状态
            $spec_price_info = [];
            $spec_price_info = $specPriceModel
                ->where([['goods_id', '=', $value['goods_id']], ['sku_key', '=', $value['spec_key']], ['spec_price_id', '=', $value['spec_price_id']]])
                ->field('`selling_price`,`achievement_bili`,`bonus_price`,`next_bonus_price`,`picurl`,`stock`,`is_onsell`,`sku`')
                ->find();
            // 判断完毕 涉及更改的 进行购物车数据的更新 包含产品图片等信息
            if ('' != $value['spec_key'] && !$spec_price_info) {
                throw new \think\Exception($value['goods_name'].'产品的'.$value['spec_value'].'规格不存在，请重新确认', 404);
            }
            $stock = $spec_price_info ? $spec_price_info['stock'] : $goods_info['stock'];
            if ($spec_price_info) {
                if ($spec_price_info['picurl'] != '/static/common/images/no_pic.png') {
                    $value['goods_pic'] = $car_data['goods_pic'] = $spec_price_info['picurl'];
                }
                $value['goods_price'] = $car_data['goods_price'] = $spec_price_info['selling_price'];
                $value['selling_price'] = $car_data['selling_price'] = $spec_price_info['selling_price'];
                $value['achievement_bili'] = $car_data['achievement_bili'] = $spec_price_info['achievement_bili'];
                $value['goods_sn'] = $spec_price_info['sku'];
                if ($is_buy == 1) {
                    $value['goods_price'] = $car_data['goods_price'] = (float)$spec_price_info['selling_price']*(float)$goods_info['vip_buy_bili'];
                    $is_edit_price = 1;
                }
            }
            $value['goods_pic'] = getShowUrl($car_data['goods_pic']);
            $value['goods_name'] = $car_data['goods_name'];
            // if ($stock < $value['buy_num']) {
            //     $value['buy_num'] = $stock;
            //     $car_data['buy_num'] = $stock;
            //     // 更新购物车数据
            //     $car_res = $carModel->find($value['car_id'])->save($car_data);
            //     throw new \think\Exception($value['goods_name'].'产品的'.$value['spec_value'].'规格库存不足，请重新确认', 404);
            // }
            $value['sub_total'] = $value['goods_price']*$value['buy_num']; // 商品小计
            $value['all_achievement_price'] = $value['sub_total']*$value['achievement_bili']; // 系统业绩计算
            $value['freight'] = 0.00;
            $value['total'] = $value['sub_total']+$value['freight'];
            // 写入订单产品数据
            $value['order_sn'] = $order_sn;
            $value['l_user_sn'] = $l_user_sn;
            $value['goods_order_sn'] = $goodsOrderModel->getCodeNo(date('YmdHis').$key, 20, 1, 'goods_order_sn'); // 产品订单id
            $value['user_sn'] = $user_sn;
            $value['shipping_type'] = $shipping_type;
            $car_res = $carModel->find($value['car_id'])->save($car_data);
            $value['need_pay'] = $value['total'];
            $value['befrom'] = $befrom;
            $store_id = $value['store_id'];
            if ($address_info) {
                $sub_order_data[$store_id]['user_address_id'] = $value['user_address_id'] = $address_info['address_id'];
                $sub_order_data[$store_id]['name'] =  $value['name'] = $address_info['name'];
                $sub_order_data[$store_id]['tel'] =  $value['tel'] = $address_info['tel'];
                $sub_order_data[$store_id]['province'] =  $value['province'] = $address_info['province'];
                $sub_order_data[$store_id]['city'] =  $value['city'] = $address_info['city'];
                $sub_order_data[$store_id]['area'] =  $value['area'] = $address_info['area'];
                $sub_order_data[$store_id]['address'] =  $value['address'] = $address_info['address'];
            }
            $sub_order_data[$store_id]['order_sn'] = $order_sn;
            $sub_order_data[$store_id]['is_edit_price'] = $is_edit_price;
            $sub_order_data[$store_id]['l_user_sn'] = $l_user_sn;
            $sub_order_data[$store_id]['store_id'] = $store_id;
            $sub_order_data[$store_id]['all_count'] =  isset($sub_order_data[$store_id]['all_count']) ? $sub_order_data[$store_id]['all_count'] : 0; // 店铺总数量
            $sub_order_data[$store_id]['all_price'] = isset($sub_order_data[$store_id]['all_price']) ? $sub_order_data[$store_id]['all_price'] : 0; // 店铺总计
            $sub_order_data[$store_id]['total_price'] = isset($sub_order_data[$store_id]['total_price']) ? $sub_order_data[$store_id]['total_price'] : 0; // 店铺商品小计
            $sub_order_data[$store_id]['total_freight'] = isset($sub_order_data[$store_id]['total_freight']) ? $sub_order_data[$store_id]['total_freight'] : 0;
            // 业绩统计
            $sub_order_data[$store_id]['all_achievement_price'] = isset($sub_order_data[$store_id]['all_achievement_price']) ? $sub_order_data[$store_id]['all_achievement_price'] : 0;
            // 需付款
            $sub_order_data[$store_id]['need_pay'] = isset($sub_order_data[$store_id]['need_pay']) ? $sub_order_data[$store_id]['need_pay'] : 0;
            $sub_order_data[$store_id]['user_sn'] = $user_sn;
            // 店铺总运费
            $sub_order_data[$store_id]['all_count'] += $value['buy_num'];
            $sub_order_data[$store_id]['all_price'] += $value['sub_total'];
            $sub_order_data[$store_id]['all_achievement_price'] += $value['all_achievement_price'];
            $sub_order_data[$store_id]['need_pay'] += $value['need_pay'];
            $sub_order_data[$store_id]['total_price'] = round(($sub_order_data[$store_id]['total_price']+$value['sub_total']), 2);
            $sub_order_data[$store_id]['shipping_type'] = $shipping_type;
            $sub_order_data[$store_id]['goods_list'][] = $value;
        }
        // 根据sub_order_data 进行运费的各种组合计算
        // var_dump($sub_order_data); die();
        if ($sub_order_data) {
            // 2022-05-11 新增 按照商品进行单件拆单
            foreach ($sub_order_data as $key => $value) {
                if ($value['goods_list']) {
                    foreach ($value['goods_list'] as $k => $val) {
                        if ($val['is_supper'] == 1) {
                            $buy_num = $val['buy_num']; // 购买数量
                          $has_num = $buy_num-1; // 剩余多少件
                          $val['buy_num'] = 1;
                            $val['sub_total'] = $val['goods_price']*$val['buy_num']; // 商品小计
                          $val['all_achievement_price'] = $val['sub_total']*$val['achievement_bili']; // 系统
                          $val['total'] = $val['sub_total']+$val['freight'];
                            // $val['goods_order_sn'] = $goodsOrderModel->getCodeNo(date('YmdHis').$key.$k, 20, 1, 'goods_order_sn'); // 产品订单id
                            $val['need_pay'] = $val['total'];
                            for ($i=1; $i <= $buy_num; $i++) {
                                $sub_order_data_arr = $value;
                                $val['goods_order_sn'] = $goodsOrderModel->getCodeNo(date('YmdHis').$key.$k.$i, 20, 1, 'goods_order_sn'); // 产品订单id
                                $sub_order_data_arr['goods_list'] = [];
                                $sub_order_data_arr['goods_list'][] = $val;
                                $sub_order_data_arr['all_count'] = 1;
                                $sub_order_data_arr['all_price'] = $val['sub_total'];
                                $sub_order_data_arr['all_achievement_price'] = $val['all_achievement_price'];
                                $sub_order_data_arr['need_pay'] = $val['need_pay'];
                                $sub_order_data_arr['total_price'] = $val['sub_total'];
                                $sub_order_data[] = $sub_order_data_arr;
                            }
                            unset($sub_order_data[$key]['goods_list'][$k]); // 从订单中剔除拆单部分的商品
                        }
                    }
                }
            }

            foreach ($sub_order_data as $key => $value) {
                if (count($value['goods_list']) <= 0) {
                    unset($sub_order_data[$key]);
                    continue;
                }
                $sub_order_data[$key]['total_freight'] = 0;
                $sub_order_sn = $subOrderModel->getCodeNo(date('YmdHis').$key, 20, 1, 'sub_order_sn');
                $sub_order_data[$key]['sub_order_sn'] = $sub_order_sn;
                $sub_order_data[$key]['all_price'] = $value['total_price'];
                $sub_order_data[$key]['need_pay'] = $value['total_price'];
                $sub_order_data[$key]['befrom'] = $befrom;
                if ($value['shipping_type'] == 2) {
                    $sub_order_data[$key]['self_code_no'] = $subOrderModel->getCodeNo('', 6, 1, 'self_code_no');
                }
                $all_num = 0;
                $avg_cost = 0.00;
                $all_cost = 0.00;
                $cost_type = 0;
                if ($address_info && $shipping_type == 1) {
                    // 根据仓库 计算仓库运费
                    $cost_info = $shippingServices->getCostPrice($address_info, $value['store_id'], $value['all_count']);
                    $cost_type = $cost_info['cost_type'];
                    $cost_price = $cost_info['cost_price']; // 仓库总运费
                    $sub_order_data[$key]['total_freight'] = $cost_price;
                    $sub_order_data[$key]['all_price'] = $cost_price+$value['total_price'];
                    $sub_order_data[$key]['need_pay'] = $cost_price+$value['total_price'];
                    $all_num = array_sum(array_column($value['goods_list'], 'buy_num')); // 获取全部数量
                    $avg_cost = floor(($cost_price/$all_num)*100)/100; // 获取每件的运费
                }
                if ($value['goods_list']) {
                    foreach ($value['goods_list'] as $k => $val) {
                        if ($cost_type == 1) {
                            $all_cost = $avg_cost*$val['buy_num'];
                        } elseif ($cost_type == 2) {
                            $all_cost = $cost_price;
                        }
                        $sub_order_data[$key]['goods_list'][$k]['sub_order_sn'] = $sub_order_sn;
                        $sub_order_data[$key]['goods_list'][$k]['freight'] = $all_cost;
                        $sub_order_data[$key]['goods_list'][$k]['freight_type'] = $cost_type; //计算方式
                        $sub_order_data[$key]['goods_list'][$k]['need_pay'] = $val['need_pay']+$all_cost;
                        $sub_order_data[$key]['goods_list'][$k]['total'] = round(($val['need_pay']+$all_cost), 2);
                    }
                }
            }
        }

        // 开始组合获取总价
        $total_price = array_sum(array_column($sub_order_data, 'total_price'));
        $all_price = array_sum(array_column($sub_order_data, 'all_price'));
        $cost = array_sum(array_column($sub_order_data, 'total_freight'));
        // 开始组合主订单数据
        $order_data['order_sn'] = $order_sn;
        $order_data['l_user_sn'] = $l_user_sn;
        $order_data['user_sn'] = $user_sn;
        $order_data['total_freight'] = round($cost, 2);
        $order_data['total'] = round($total_price, 2);
        $order_data['need_pay'] = round($all_price, 2);
        $order_data['befrom'] = $befrom;
        $order_data['shipping_type'] = $shipping_type;
        $order_data['user_address_id'] = $address_id;
        $order_data['name'] = $address_info['name'];
        $order_data['is_edit_price'] = $is_edit_price;
        $order_data['tel'] = $address_info['tel'];
        $order_data['province'] = $address_info['province'];
        $order_data['city'] = $address_info['city'];
        $order_data['area'] = $address_info['area'];
        $order_data['address'] = $address_info['address'];
        $result['order_data'] = $order_data;
        $result['sub_order_data'] = $sub_order_data;
        return $result;
    }
    /**
     * @xk 同步子订单数据
     *
     * @method syncSubOrder
     * @param  [type]       $order_id                  [description]
     * @param  [type]       $sub_order_data            [description]
     * @return [type]       [description]
     * @Time   2021-10-22
     * @City   青岛
     * @Author xkyinzhe     <zhonghuaxinxing@sina.cn>
     */
    public static function syncSubOrder($order_id, $sub_order_data, $content)
    {
        $subOrderModel = new SubOrderModel();
        $goodsOrderModel = new GoodsOrderModel();
        $carModel = new CarModel();
        $goodsModel = new GoodsModel();
        $specPriceModel = new SpecPriceModel();
        $taskService = new Task();
        if (!$sub_order_data) {
            throw new \think\Exception("系统错误子订单不存在", 404);
        }
        foreach ($sub_order_data as $key => $value) {
            $sub_order_data = [];
            $sub_order_data = $value;
            $sub_order_data['content'] = $content;
            unset($sub_order_data['goods_list']);
            $sub_res = $subOrderModel->create($sub_order_data);
            if ($value['goods_list']) {
                foreach ($value['goods_list'] as $k => $val) {
                    $goods_res = $goodsOrderModel->create($val);
                    // 执行购物车数据替换
                    $car_res = $carModel
                        ->find($val['car_id'])
                        ->save(['order_sn'=>$val['order_sn'],'sub_order_sn'=>$val['sub_order_sn'],'goods_order_sn'=>$val['goods_order_sn'],'status'=>1]);
                    // 执行库存扣除
                    // $goods_res = $goodsModel
                    // ->where([['goods_id','=',$val['goods_id']]])
                    // ->dec('stock', (int)$val['buy_num'])
                    // ->update();
                    $goods_res = $goodsModel
                    ->where([['goods_id','=',$val['goods_id']]])
                    ->inc('shell_num', (int)$val['buy_num'])
                    ->update();
                    if (isset($val['spec_key'])) {
                        // 执行规格库存扣除
                      //   $spec_res = $specPriceModel
                      // ->where([['goods_id','=',$val['goods_id']],['sku_key','=',$val['spec_key']],['spec_price_id','=',$val['spec_price_id']]])
                      // ->dec('stock', (int)$val['buy_num'])
                      // ->update();
                    }
                }
            }
            $msgData = ['time' => date('YmdHis'), 'msgId' => $value['sub_order_sn'], 'jobAction' => 'orderCancel'];
            $delay = config('web_config.cancel_hour')*3600;
            $taskService->put($msgData, $delay);
        }
    }
    /**
     * @xk 同步订单支付结果
     *
     * @method syncSubOrderPay
     * @param  [type]          $order_sn                  [description]
     * @return [type]          [description]
     * @Time   2021-10-22
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public static function syncSubOrderPay($order_sn)
    {
        $orderModel = new OrderModel();
        $subOrderModel = new SubOrderModel();
        $goodsOrderModel = new GoodsOrderModel();
        $userModel = new UserModel();
        $userUpLogModel = new UserUpLogModel();
        $taskService = new Task();
        $userServices = new UserServices();
        $sendMsgServices = new SendMsg();
        $orderServices = new OrderServices();
        // $financeServices = new FinanceServices();
        $sendMsg = new SendMsg();
        if ($order_sn == '') {
            throw new \think\Exception("订单信息不存在", 404);
        }
        $order_info = $orderModel
                    ->where([['order_sn','=',$order_sn]])
                    ->field('`order_id`,`order_sn`,`user_sn`,`shipping_type`,`pay_time`,`pay_type`,`pay_price`,`pay_code`,`pay_style`,`pay_order_sn`,`pay_status`,`status`,`delivery_time`,`l_user_sn`')
                    ->find();
        if (!$order_info) {
            throw new \think\Exception("【".$order_sn."】主单号有误，无法同步", 404);
        }
        // 判断当前会员的等级 如果是游客 则视为首单
        $user_info = $userModel
                  ->where([['user_sn','=',$order_info['user_sn']]])
                  ->field('`user_id`,`user_name`,`user_sn`,`l_user_sn`,`level`,`is_all_bind`,`is_buy`')
                  ->find();
        if (!$user_info) {
            throw new \think\Exception("下单用户异常，无法同步", 404);
        }
        $is_buy = 0;
        $is_edit_price = 0;
        if ($user_info['is_buy'] == 1) {
            $is_buy = 1; // 之前存在 则这笔订单一定是复购
        }
        if ($is_buy == 0) {
            $user_res = $userModel->where([['user_sn','=',$user_info['user_sn']]])->save(['user_id'=>$user_info['user_id'],'level'=>2,'is_buy'=>1]); // 用户升级为vip 同时关系永久绑定
            // 进行升级操作
            $check_now_time =  checkNowTime();
            if ($check_now_time == 1) {
                $msgData = ['time' => date('YmdHis'), 'msgId' => $user_info['user_sn'],'l_user_sn'=>$user_info['l_user_sn'],'level'=>1,'count'=>'desc', 'jobAction' => 'syncPayOverCheck'];
                $msgDatax = ['time' => date('YmdHis'), 'msgId' => $user_info['user_sn'],'l_user_sn'=>$user_info['l_user_sn'],'level'=>2,'count'=>'inc', 'jobAction' => 'syncPayOverCheck'];
                $delay = 30;
                $taskService->put($msgData, $delay);
                $taskService->put($msgDatax, $delay);
            }
            // 当前 订单时首购订单 则自动取消该会员全部未付款订单
            $cancel_order_data = [];
            // 未付款 状态直接取消
            $cancel_order_data['status'] = 6; // 订单取消
            $cancel_order_data['cancel_time'] = date('Y-m-d H:i:s'); // 取消订单时间
            $cancel_condition = [];
            $sub_order_arr = $subOrderModel->where([['user_sn','=',$user_info['user_sn']],['status','=',0],['order_sn','<>',$order_sn]])->column('sub_order_sn');
            $res = $orderModel->where([['user_sn','=',$user_info['user_sn']],['status','=',0],['order_sn','<>',$order_sn]])->save($cancel_order_data);
            $res = $subOrderModel->where([['user_sn','=',$user_info['user_sn']],['status','=',0],['order_sn','<>',$order_sn]])->save($cancel_order_data);
            $order_goods_res = $goodsOrderModel
                              ->where([['user_sn','=',$user_info['user_sn']],['status','=','0.1'],['order_sn','<>',$order_sn]])
                              ->save(['status'=>'6.1','order_status'=>6]);
            // 需要恢复 产品对应的库存
            if ($sub_order_arr) {
                foreach ($sub_order_arr as $key => $value) {
                    $orderServices->syncStock($value, 'inc'); // 取消订单
                }
            }
            // 订单取消结束
        }
        if ($user_info['is_all_bind'] == 0) {
            // 没有永久绑定关系的用户 操作永久绑定关系
            $user_res = $userModel->where([['user_sn','=',$user_info['user_sn']]])->save(['is_all_bind'=>1]); // 用户升级为vip 同时关系永久绑定
            // 永久绑定推送通知 未作
            $new_content = '易得悠品新会员【'.$user_info['user_name'].'】于'.date('Y-m-d H:i:s').'成为您的会员，会员号为【'.$user_info['user_sn'].'】,感谢您的支持与帮助';
            $push_data = [];
            $push_data['user_name'] = $user_info['user_name'];
            $push_data['create_time'] = date('Y-m-d H:i:s');
            // 给上级推送
            $sendMsgServices->sendPushMsg($user_info['l_user_sn'], '会员注册成功通知', $new_content, 1, $push_data);
        }
        // 所有当前状态 属于未支付的
        $sub_order_list = $subOrderModel
                        ->where([['order_sn','=',$order_sn],['status','=',0]])
                        ->column('sub_order_sn');
        if ($sub_order_list && count($sub_order_list) <= 0) {
            throw new \think\Exception("【".$order_sn."】主单号没有可以同步的子单号", 404);
        }
        $sub_order_data = $order_goods_data = [];
        $sub_order_data['pay_code'] = $order_info['pay_code'];
        $sub_order_data['pay_type'] = $order_info['pay_type'];
        $sub_order_data['pay_time'] = $order_info['pay_time'];
        $sub_order_data['pay_status'] = $order_info['pay_status'];
        $sub_order_data['pay_order_sn'] = $order_info['pay_order_sn'];
        $sub_order_data['pay_price'] = $order_info['pay_price']; // 订单实际支付金额
        $sub_order_data['delivery_time'] = $order_info['delivery_time'];
        $sub_order_data['l_user_sn'] = $user_info['l_user_sn']; // 重新写入 绑定的上级信息
        $sub_order_data['status'] = 1;
        $sub_order_data['is_edit_price'] = 1; // 付款完成 订单则无需再次进行价格修改
        $sub_order_data['pay_style'] = $order_info['pay_style'];
        $sub_order_data['is_buy'] = $is_buy; // 0=首购 1=复购
        $order_goods_data = $sub_order_data;
        $order_goods_data['status'] = 1.1;
        // 同步子订单数据
        $order_res = $subOrderModel
                  ->where([['order_sn','=',$order_sn]])
                  ->save($sub_order_data);
        // 同步商品订单数据
        $order_goods_res = $goodsOrderModel
                        ->where([['order_sn','=',$order_sn]])
                        ->save($order_goods_data);
        // 开始执行广告佣金预发放
        if ($user_info['l_user_sn'] > 0) {
            foreach ($sub_order_list as $key => $value) {
                $msgDatax = ['time' => date('YmdHis'), 'msgId' => $value,'user_sn'=>$user_info['user_sn'],'l_user_sn'=>$user_info['l_user_sn'],'act'=>'create', 'jobAction' => 'syncBackMoney'];
                $delay = 20;
                $taskService->put($msgDatax, $delay);
            }
        }
    }

    /**
     * @xk 子订单支付成功后 同步商品状态
     *
     * @method syncOrderGoodsStatus
     * @param  [type]               $sub_order_sn              [description]
     * @return [type]               [description]
     * @Time   2021-09-16
     * @City   青岛
     * @Author xkyinzhe             <zhonghuaxinxing@sina.cn>
     */
    public static function syncOrderGoodsStatus($sub_order_sn)
    {
        if ($sub_order_sn == '') {
            throw new \think\Exception("需要同步库存的商品不存在", 404);
        }
        $subOrderModel = new SubOrderModel();
        $goodsOrderModel = new GoodsOrderModel();
        $userModel = new UserModel();
        $userUpLogModel = new UserUpLogModel();
        $userServices = new UserServices();
        $taskService = new Task();
        $sendMsg = new SendMsg();
        $order_info = $subOrderModel
                      ->where([['sub_order_sn','=',$sub_order_sn]])
                      ->field('`sub_order_id`,`sub_order_sn`,`user_sn`,`shipping_type`,`pay_time`,`pay_type`,`pay_price`,`pay_code`,`pay_order_sn`,`pay_status`,`status`,`delivery_time`,`l_user_sn`')
                      ->find();
        // 判断当前会员的等级 如果是游客 则视为首单
        $user_info = $userModel
                      ->where([['user_sn','=',$order_info['user_sn']]])
                      ->field('`user_id`,`user_name`,`user_sn`,`l_user_sn`,`level`,`is_all_bind`,`is_buy`')
                      ->find();
        if (!$user_info) {
            throw new \think\Exception("下单用户异常，无法同步", 404);
        }
        $is_buy = 0;
        if ($user_info['is_buy'] == 1) {
            $is_buy = 1; // 之前存在 则这笔订单一定是复购
        }
        if ($is_buy == 0) {
            $user_res = $userModel->where([['user_sn','=',$user_info['user_sn']]])->save(['user_id'=>$user_info['user_id'],'level'=>2,'is_buy'=>1]); // 用户升级为vip 同时关系永久绑定
            // 进行升级操作
            $msgData = ['time' => date('YmdHis'), 'msgId' => $user_info['user_sn'],'l_user_sn'=>$user_info['l_user_sn'],'level'=>1,'count'=>'desc', 'jobAction' => 'syncPayOverCheck'];
            $msgDatax = ['time' => date('YmdHis'), 'msgId' => $user_info['user_sn'],'l_user_sn'=>$user_info['l_user_sn'],'level'=>2,'count'=>'inc', 'jobAction' => 'syncPayOverCheck'];
            $delay = 30;
            $taskService->put($msgData, $delay);
            $taskService->put($msgDatax, $delay);
        }
        if ($user_info['is_all_bind'] == 0) {
            // 没有永久绑定关系的用户 操作永久绑定关系
            $user_res = $userModel->where([['user_sn','=',$user_info['user_sn']]])->save(['is_all_bind'=>1]); // 用户升级为vip 同时关系永久绑定
        }
        $goods_order_data = [];
        $goods_order_data['is_buy'] = $is_buy;
        $goods_order_data['pay_price'] = $order_info['pay_price'];
        $goods_order_data['pay_order_sn'] = $order_info['pay_order_sn'];
        $goods_order_data['pay_code'] = $order_info['pay_code'];
        $goods_order_data['pay_type'] = $order_info['pay_type'];
        $goods_order_data['pay_time'] = $order_info['pay_time'];
        $goods_order_data['pay_status'] = $order_info['pay_status'];
        if ($order_info && $order_info['pay_status'] == 1) {
            // 开始获取当前订单状态
            if ($order_info['status'] == 1) {
                $goods_order_data['status'] = 1.1;
                $goods_order_data['order_status'] = 1;
            } elseif ($order_info['status'] == 2) {
                $goods_order_data['status'] = 2.1;
                $goods_order_data['order_status'] = 2;
                $goods_order_data['delivery_time'] = $order_info['delivery_time'];
            }
            $goodsOrderModel->where([['sub_order_sn','=',$sub_order_sn]])->save($goods_order_data);
        }
        // 开始执行广告佣金预发放
        if ($order_info['l_user_sn'] > 0) {
            $userServices->syncAdvBackMoney($sub_order_sn, $user_info['user_sn'], $order_info['l_user_sn'], 'create');
        }
    }
    /**
     * @xk 执行同步商品库存
     *
     * @method syncStock
     * @param  [type]     $sub_order_sn              [description]
     * @param  [type]     $act                       [description]
     * @return [type]     [description]
     * @Time   2021-09-07
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public static function syncStock($sub_order_sn='', $act='inc')
    {
        if ($sub_order_sn == '') {
            throw new \think\Exception("需要同步库存的商品不存在", 404);
        }
        $goodsOrderModel = new GoodsOrderModel();
        $goodsModel = new GoodsModel();
        $specPriceModel = new SpecPriceModel();
        $goods_list = $goodsOrderModel
                    ->where([['sub_order_sn','=',$sub_order_sn]])
                    ->field('`goods_id`,`buy_num`,`spec_key`,`spec_price_id`')
                    ->select()
                    ->toArray();
        if (!$goods_list) {
            throw new \think\Exception("需要同步的商品不存在", 404);
        }
        foreach ($goods_list as $key => $value) {
            if ($value['goods_id'] >0 && (int)$value['buy_num'] > 0) {
                // $goods_res = $goodsModel
                //         ->where([['goods_id','=',$value['goods_id']]])
                //         ->inc('stock', (int)$value['buy_num'])
                //         ->update();
                $goods_res = $goodsModel
                            ->where([['goods_id','=',$value['goods_id']]])
                            ->dec('shell_num', (int)$value['buy_num'])
                            ->update();
                // if (isset($value['spec_key'])) {
                //     // 执行规格库存增加
                //     $spec_res = $specPriceModel
                //                 ->where([['goods_id','=',$value['goods_id']],['sku_key','=',$value['spec_key']],['spec_price_id','=',$value['spec_price_id']]])
                //                 ->inc('stock', (int)$value['buy_num'])
                //                 ->update();
                // }
            }
        }
    }
    /**
     * @xk 执行退款后 退款状态查询 成功 查看订单状态是否需要更新 回滚库存
     *
     * @method syncRefundResult
     * @param  string           $refund_order_sn           [description]
     * @return [type]           [description]
     * @Time   2021-09-18
     * @City   青岛
     * @Author xkyinzhe         <zhonghuaxinxing@sina.cn>
     */
    public static function syncRefundResult($refund_order_sn = '')
    {
        $refundOrderModel = new RefundOrderModel();
        $userModel = new UserModel();
        $userServices = new UserServices();
        $condition = [];
        $condition[] = ['refund_order_sn','=',$refund_order_sn];
        $refund_info = $refundOrderModel
                    ->where($condition)
                    ->field('`type`,`status`,`goods_order_sn`,`sub_order_sn`,`user_sn`')
                    ->find();
        if (!$refund_info) {
            throw new \think\Exception("=======【".$refund_order_sn."】=======售后订单不存在===========", 404);
        }
        if ($refund_info['status'] != 1.3 && $refund_info['status'] != 2.5) {
            throw new \think\Exception("====【".$refund_order_sn."】==售后订单未完成退款操作无需其他处理==", 404);
        }
        $goodsOrderModel = new GoodsOrderModel();
        $goodsModel = new GoodsModel();
        $specPriceModel = new SpecPriceModel();
        $subOrderModel = new SubOrderModel();
        $goods_info = $goodsOrderModel
                  ->where([['goods_order_sn','=',$refund_info['goods_order_sn']]])
                  ->field('`goods_id`,`buy_num`,`spec_key`,`spec_price_id`,`l_user_sn`')
                  ->find()
                  ->toArray();
        if (!$goods_info) {
            throw new \think\Exception("需要同步的商品不存在", 404);
        }
        $goods_status = 5.13; // 退款成功
        if ($refund_info['type'] == 2) {
            $goods_status = 5.25;
        }
        $order_goods_Res = $goodsOrderModel
                          ->where([['goods_order_sn','=',$refund_info['goods_order_sn']]])
                          ->save(['status'=>$goods_status]);
        $goods_res = $goodsModel
                  ->where([['goods_id','=',$goods_info['goods_id']]])
                  ->dec('shell_num', (int)$goods_info['buy_num'])
                  ->update();
        $goods_condition = [];
        $goods_condition[] = ['status','in','1.1,2.1,3.1,4.1,5.1,5.11,5.2,5.21,5.23,5.24,5.3,5.31,5.33,5.34'];
        $goods_condition[] = ['user_sn','=',$refund_info['user_sn']];
        $goods_count = $goodsOrderModel->where($goods_condition)->count();
        if ($goods_count <= 0) {
            // 新增退款结果判断 如果当前用户还存在消费记录 则判定该用户已经完成首购
            $user_purchase_order_price = $userModel
                                          ->where([['user_sn','=',$refund_info['user_sn']]])
                                          ->field('purchases_order_price')
                                          ->find();
            if ($user_purchase_order_price['purchases_order_price'] <= 0) {
                // 没有正在进行中的产品
                $userModel->where([['user_sn','=',$refund_info['user_sn']]])->save(['is_buy'=>0]);
            } else {
                $userModel->where([['user_sn','=',$refund_info['user_sn']]])->save(['is_buy'=>1]);
            }
        }
        $search_condition = [];
        $search_condition[] = ['status','in','1.1,2.1,3.1,4.1,5.1,5.11,5.2,5.21,5.23,5.24,5.3,5.31,5.33,5.34'];
        $search_condition[] = ['sub_order_sn','=',$refund_info['sub_order_sn']];
        $all_count = $goodsOrderModel->where($search_condition)->count();
        if ($goods_info['l_user_sn'] > 0) {
            $userServices->syncAdvBackMoney($refund_info['sub_order_sn'], $refund_info['user_sn'], $goods_info['l_user_sn'], 'refund', $refund_info['goods_order_sn'], $all_count);
        }
    }
    /**
     * @xk 订单确认收货成功后 开始执行业绩统计
     *
     * @method syncFinance
     * @param  string      $sub_order_sn              [description]
     * @return [type]      [description]
     * @Time   2021-10-28
     * @City   青岛
     * @Author xkyinzhe    <zhonghuaxinxing@sina.cn>
     */
    public static function syncFinance($sub_order_sn = '')
    {
        $subOrderModel = new SubOrderModel();
        $userServices = new UserServices();
        $goodsOrderModel = new GoodsOrderModel();
        if ($sub_order_sn == '') {
            throw new \think\Exception("执行业绩统计订单不存在", 404);
        }
        $condition = [];
        $condition[] = ['sub_order_sn','=',$sub_order_sn];
        $order_condition = [];
        $order_condition[] = ['sub.sub_order_sn','=',$sub_order_sn];
        $order_info = $subOrderModel
                      ->alias('sub')
                      ->leftJoin('user u', 'u.user_sn=sub.user_sn')
                      ->where($order_condition)
                      ->field('sub.`sub_order_sn`,sub.`user_sn`,sub.`status`,sub.`is_finance`,sub.`is_buy`,u.`level`')
                      ->find();
        if (!$order_info) {
            throw new \think\Exception("执行业绩统计的订单异常", 404);
        }
        if ($order_info['is_finance'] != 0) {
            throw new \think\Exception("当前订单业绩结算状态异常", 404);
        }
        $goods_condition = [];
        $goods_condition = $condition;
        $goods_condition[] = ['status','=','3.1']; // 所有处于收货状态的商品
        $all_achievement_price = $goodsOrderModel->where($goods_condition)->sum('all_achievement_price');
        if ($all_achievement_price > 0) {
            // 开始写入会员业绩统计
            // 优先执行会员广告佣金结算和推广佣金结算 其次执行分红结算
            $push_user_sn = $user_sn = $order_info['user_sn'];
            $userServices->syncBackMoney($sub_order_sn, $push_user_sn, $user_sn, $all_achievement_price, $order_info['is_buy'], $order_info['level']);
            $subOrderModel->where($condition)->save(['is_finance'=>1,'finance_time'=>date('Y-m-d H:i:s')]);
            $goodsOrderModel->where($goods_condition)->save(['is_finance'=>1,'finance_time'=>date('Y-m-d H:i:s')]);
        } else {
            $subOrderModel->where($condition)->save(['is_finance'=>1,'is_avg_finance'=>1,'avg_finance_time'=>date('Y-m-d H:i:s')]);
            $goodsOrderModel->where($goods_condition)->save(['is_finance'=>1,'finance_time'=>date('Y-m-d H:i:s')]);
        }
    }
    /**
     * @xk 执行退款操作
     *
     * @method syncRefundPay
     * @param  [type]        $refund_order_sn           [description]
     * @return [type]        [description]
     * @Time   2021-11-02
     * @City   青岛
     * @Author xkyinzhe      <zhonghuaxinxing@sina.cn>
     */
    public static function syncRefundPay($refund_order_sn = '')
    {
        $refundOrderModel = new RefundOrderModel();
        $userServices = new UserServices();
        $orderServices = new OrderServices();
        // 第一步： 获取售后订单状态
        $refund_info = $refundOrderModel
                    ->alias('ref')
                    ->leftJoin('goodsOrder go', 'go.goods_order_sn = ref.goods_order_sn')
                    ->where([['refund_order_sn','=',$refund_order_sn]])
                    ->field('ref.`refund_order_sn`,ref.`type`,ref.`user_sn`,ref.`status`,ref.`refund_check_price`,ref.`sub_order_sn`,ref.`order_sn`,ref.`goods_order_sn`,go.`pay_order_sn`,go.`pay_type`,go.`pay_code`,go.`pay_price`,go.`pay_style`')
                    ->find();
        if (!$refund_info) {
            throw new \think\Exception("售后订单不存在", 404);
        }
        // if ($refund_info['status'] != 1.1 && $refund_info['status'] != 2.4) {
        //     throw new \think\Exception("当前售后订单不处于可以退款状态", 404);
        // }
        // dump($refund_info['pay_type']); die();
        // 第二步： 判断支付方式
        // 第三步： 执行微信/余额退款
        switch ($refund_info['pay_type']) {
          case '1':
            Unionpay::orderRefundPay($refund_info);
            break;
          case '2':
            Unionpay::orderRefundPay($refund_info);
            break;
          case '3':
            $userServices->syncRefundMoney($refund_info); // 开始同步余额支付退款
            break;
          case '4':
            Unionpay::orderRefundPay($refund_info);
            break;
          default:
            throw new \think\Exception("用户付款渠道异常，请联系处理", 404);

            break;
        }
    }
    /**
     * @xk 执行平台付款的退款
     * @method  doSyncRefundMoney
     * @param   [type] $refund_info  [description]
     * @return  [type] [description]
     * @Version V5.0
     * @Time    2021-11-13
     * @City    青岛
     * @Author  xkyinzhe <zhonghuaxinxing@sina.cn>
     */
    public static function doSyncRefundMoney($data)
    {
        $refundOrderModel = new RefundOrderModel(); // 售后处理模型
        $orderServices = new OrderServices();
        $financeServices = new FinanceServices();
        $user_sn = isset($data['user_sn']) ? $data['user_sn'] : '';
        $refund_order_sn = isset($data['refund_order_sn']) ? $data['refund_order_sn'] : '';
        $need_pay = isset($data['refund_check_price']) ? $data['refund_check_price'] : 0.00;
        if (!$data) {
            throw new \think\Exception("售后订单异常", 404);
        }
        if ($data['status'] != 1.1 && $data['status'] != 2.4) {
            throw new \think\Exception("当前售后订单不处于可以退款状态", 404);
        }
        if ($user_sn == '') {
            throw new \think\Exception("申请用户异常，请重新处理", 404);
        }
        if ($refund_order_sn == '') {
            throw new \think\Exception("售后订单不存在", 404);
        }
        if ($need_pay <= 0) {
            throw new \think\Exception("审核退款金额小于0 无需执行退款操作", 404);
        }
        $order_data = [];
        $order_data['refund_price'] = $need_pay;
        $order_data['refund_code'] = $refundOrderModel->getCodeNo(date('YmdHis'), 15, 1, 'refund_code');
        $order_data['finish_time'] = date('Y-m-d H:i:s');
        // 开始执行 相关操作
      $order_data['status'] = 1.3; // 退款完成
      if ($data['type'] == 2) {
          $order_data['status'] = 2.5; // 退货完成
      }
        $refund_order_res = $refundOrderModel->where([['refund_order_sn','=',$refund_order_sn]])->save($order_data);
        // 写入余额财务记录
        $finance_data = [];
        $finance_data['relation_num'] = $refund_order_sn;
        $finance_data['relation_user_num'] = $user_sn;
        $finance_data['entry'] = 2;
        $finance_data['money'] = $need_pay;
        $finance_data['pay_order_sn'] = isset($data['pay_order_sn']) ? $data['pay_order_sn'] : '';
        $finance_data['content'] = '用户申请平台支付退款，平台支出';
        $finance_data['pay_type'] = 4;
        $finance_data['act'] = 4;
        $financeServices->syncFinance($finance_data);
        $orderServices->syncRefundResult($refund_order_sn);
        return true;
    }

    /**
     * @xk 执行订单金额重新计算
     * @method          syncOrderPrice
     * @param           [type] $order_sn [description]
     * @return          [type] [description]
     * @Version：V6.0
     * @Author：xkyinzhe <zhonghuaxinxing@sina.cn>
     * @City：青岛
     * @Time：2023-01-17
     */
    // public static function syncOrderPrice($order_sn)
    // {
    //     $orderModel = new OrderModel();
    //     $subOrderModel = new SubOrderModel();
    //     $goodsOrderModel = new GoodsOrderModel();
    //     $sub_order_list = $subOrderModel
    //                      ->alias('sub')
    //                      ->leftJoin('user u', 'u.user_sn = sub.user_sn')
    //                      ->where([['sub.order_sn','=',$order_sn]])
    //                      ->field('sub.`sub_order_sn`,u.`is_buy`,sub.`total_freight`,sub.`is_edit_price`')
    //                      ->select()
    //                      ->toArray();
    //     if ($sub_order_list) {
    //         $all_price = 0.00;
    //         $all_achievement_price = 0.00;
    //         $is_can_update = 0;
    //         foreach ($sub_order_list as $key => $value) {
    //             if ($value['is_buy'] == 0 || $value['is_edit_price'] == 1) {
    //                 $is_can_update = 1;
    //                 break;
    //             }
    //             $goods_order_list = $goodsOrderModel
    //                            ->alias('og')
    //                            ->leftJoin('goods g', 'g.goods_id = og.goods_id')
    //                            ->where([['og.order_sn','=',$order_sn],['og.sub_order_sn','=',$value['sub_order_sn']]])
    //                            ->field('og.`order_goods_id`,og.`goods_price`,og.`goods_id`,og.`spec_price_id`,g.`vip_buy_bili`,og.`total`,og.`achievement_bili`,og.`freight`,og.`sub_total`')
    //                            ->select()
    //                            ->toArray();
    //             if ($goods_order_list) {
    //                 $sub_all_price = 0.00;
    //                 $sub_all_achievement_price= 0.00;
    //                 foreach ($goods_order_list as $k => $val) {
    //                     $goods_price = $val['goods_price']*$val['vip_buy_bili']; // 计算折扣价格
    //                     $goods_order_data = [];
    //                     $goods_order_data['is_edit_price'] = 1;
    //                     $goods_order_data['goods_price'] = $goods_price; // 最终的计算价格
    //                     $goods_order_data['total'] = $val['sub_total']*$val['vip_buy_bili']+$val['freight'];
    //                     $goods_order_data['sub_total'] = $val['sub_total']*$val['vip_buy_bili'];
    //                     $goods_order_data['order_goods_id'] = $val['order_goods_id'];
    //                     $goods_order_data['all_achievement_price'] =   $goods_order_data['total']*$val['achievement_bili'];
    //                     $goodsOrderModel->find($val['order_goods_id'])->save($goods_order_data);
    //                     $sub_all_price += $goods_order_data['sub_total'];
    //                     $sub_all_achievement_price += $goods_order_data['all_achievement_price'];
    //                 }
    //                 $sub_order_data = [];
    //                 $sub_order_data['total_price'] = $sub_all_price;
    //                 $sub_order_data['all_price'] = $sub_all_price+$value['total_freight'];
    //                 $sub_order_data['need_pay'] = $sub_all_price+$value['total_freight'];
    //                 $sub_order_data['all_achievement_price'] = $sub_all_achievement_price;
    //                 $sub_order_data['is_edit_price'] = 1;
    //                 $all_price += $sub_all_price;
    //                 $all_achievement_price += $sub_all_achievement_price;
    //                 $subOrderModel->where([['sub_order_sn','=',$value['sub_order_sn']]])->save($sub_order_data);
    //             }
    //         }
    //         if ($is_can_update == 0) {
    //             $order_info = $orderModel->where([['order_sn','=',$order_sn]])->field('`total_freight`')->find();
    //             $order_data = [];
    //             $order_data['total'] = $all_price;
    //             $order_data['total_freight'] = $order_info['total_freight'];
    //             $order_data['need_pay'] = $all_price + $order_info['total_freight'];
    //             $sub_order_data['is_edit_price'] = 1;
    //             $order_info->save($order_data);
    //         }
    //     }
    // }
}
